﻿<#
#=======================================================================================
# Name: CreateProjectStructure.ps1
# Version: 0.2
# Author: Raphael Perez - raphael@rflsystems.co.uk
# Date: 10/01/2013
# Comment: This script will create Folders and Collection infrastructure for the project
# 
# Updates:
#        0.1 - Raphael Perez - 05/10/2012 - Initial Script
#        0.2 - Raphael Perez - 10/01/2013
#                      - Added try/finally
#
# Usage:
#		 Option 1: powershell.exe -ExecutionPolicy Bypass .\CreateProjectStructure.ps1 [Parameters]
#        Option 2: Open Powershell and execute .\CreateProjectStructure.ps1 [Parameters]
#
# Parameters: (All parameters are optional, if you do not use, script will ask you to provide the information)
#        sdkServer - server that will be the sdk server
#        ProjectName - Name of the project
#        GlobalProject - y/n - Create a Global Project
#        Country - Country Code (used when GlobalProject = n)
#        Location - State, City, Area, Datacenter, etc... - (used when GlobalProject = n) (use ',' to add multiple locations)
#        WQLWhere
#
# Examples:
#        ./InstallSCCMSite -siteinstallationtype '2' -sdkServer 'sccm01.mylab.com' -sitecode '001' -sitename '001 Site' -localdatabase 'y' -changeDatabase 'y' -InitialSize 5 -NumberOfFiles 1 -useclientpush 'y' -ClientPushAccount 'sccmpush' -ClientPushAccountPassword 'Pa$$w0rd' -usenetworkaccessaccount 'y' -NetworkAccessAccount 'sccmna' -NetworkAccessAccountPassword 'Pa$$w0rd' -createServerBoundary 'y' -forestdiscovery 'n' -systemdiscovery 'n' -userdiscovery 'n' -groupdiscovery 'n' -createcollections 'y' -ParentSiteCode '' -SecondaryServerNetbiosName '' -ProjectName 'Matrix 64'
#        - install primary site stand alone, the sdk server will be sccm01.mylab.com, sitecode 001, site name 001 Site, using local database
#        - the initial database size will be 5gb and it will be only 1 file, client push and network account will be set up
#        - will create a boundary (and boundary group) as well as collections and folders (device and user collections)
#        - will not enable any discovery
#=======================================================================================
#>
PARAM(
    $sdkServer = '',
    $ProjectName = '',
    $GlobalProject = '',
    $Country = '',
    $Location = '',
    $WQLWhere = ''
)
try
{
    $ErrorActionPreference = "Stop"
    $maxretry = 5
    $MediaFolder = $MediaFolder = (Get-Item (Get-Location).Path).Parent.FullName
    if ($MediaFolder -eq '') { (Get-Location).Path }
    if ($mediaFolder.substring($mediaFolder.length-1) -ne '\') { $mediaFolder += '\' }        

    if (!(Test-Path -Path .\Functions.ps1))
    {
        Write-Host "Module Functions.ps1 does not exist on the current folder, no futher action taken" -ForegroundColor Red
    }
    else
    {
        Import-Module -name .\Functions.ps1
    }

    $scriptName = ($MyInvocation.MyCommand.Name)
    $StrDateTime = Get-Date -uformat "%d%m%Y-%H%M"
    $path = $MediaFolder + "_Logs\" + ($MyInvocation.MyCommand.Name -replace '.ps1', '') + ".log"
    $component = ($MyInvocation.MyCommand.Name -replace '.ps1', '')
    New-Item ($MediaFolder + '_Logs') -type directory -force | out-null 
    try
    {
        New-Item ($MediaFolder + '_Logs\Test.log') -type file -force | out-null 
        Remove-Item ($MediaFolder + '_Logs\Test.log') -force | out-null 
    }
    catch
    {
        Write-Host "Unable to read/write file on $MediaFolder folder, no futher action taken" -ForegroundColor Red
        Exit    
    }

    [Environment]::SetEnvironmentVariable("SEE_MASK_NOZONECHECKS", "1", "Process")

    if (!(Test-PowerShell64)) { Exit }
    if (!(Test-IsMediaFolderExist -MediaFolder $MediaFolder)) { Exit }

    $logsize = 10

    $computerinfo = Get-WmiObject Win32_ComputerSystem
    $computerfqdn = $computerinfo.name + '.' + $computerinfo.Domain

    if ((gwmi  -namespace 'root\sms' -class 'SMS_ProviderLocation' -ErrorAction SilentlyContinue) -eq $null)
    { $sdkServer = (BuildAnswer -return $sdkServer -Question "SDK Server" -allowblank $false -errorMsg 'SDK Server') }
    else { $sdkserver = (BuildAnswer -return $sdkserver -question 'SDK Server' -default $computerfqdn) }

    $sitecode = (gwmi -namespace 'root\sms' -class 'SMS_ProviderLocation' -ComputerName $sdkserver).SiteCode

    $ProjectName = (BuildAnswer -return $ProjectName -Question "Project Name" -allowblank $false -errorMsg 'Project Name')
    $GlobalProject = (BuildAnswer -return $GlobalProject -Question "Global Project" -options "y/n" -default "y").ToLower()

    if ($GlobalProject -eq 'n')
    {
        $Country = (BuildAnswer -return $Country -Question "Country Code" -allowblank $false -errorMsg 'Country Code')
        $Location = (BuildAnswer -return $Location -Question "Location" -allowblank $false -errorMsg 'Location')
        if (($Location.split(',')).Count -eq 1)
        { $WQLWhere = (BuildAnswer -return $WQLWhere -Question "WQL Where (ie: SMS_R_System.SMSAssignedSites = 'P01')" -allowblank $false -errorMsg 'WQL Where') }
    }

    Write-Log -Message "MediaFolder: $MediaFolder"
    Write-Log -Message "sdkServer: $sdkServer"
    Write-Log -Message "ProjectName: $ProjectName"
    Write-Log -Message "GlobalProject: $GlobalProject"
    Write-Log -Message "Country: $Country"
    Write-Log -Message "Location: $Location"
    Write-Log -Message "WQLWhere: $WQLWhere"

    if ($GlobalProject -eq 'y')
    { 
        $FolderName = "Global/$ProjectName" 
        
        Write-log -message ('Creating CM User Folders...Starting')
        $nullreturn = Add-CMFolder -sdkServer $sdkServer -sitecode $siteCode -FolderName "Software Deployment" -FolderType 5001
        $nullreturn = Add-CMFolder -sdkServer $sdkServer -sitecode $siteCode -FolderName "Client Settings" -FolderType 5001
        $nullreturn = Add-CMFolder -sdkServer $sdkServer -sitecode $siteCode -FolderName "Settings Management" -FolderType 5001
        $nullreturn = Add-CMFolder -sdkServer $sdkServer -sitecode $siteCode -FolderName "Other" -FolderType 5001
        Write-log -message ('Creating CM User Folders...Done')
        
        CreateProjectStructure -sdkServer $sdkServer -sitecode $siteCode -FolderName $FolderName -globalproject 'y'
    }
    else
    {
        $aloc = $Location.split(',')
        foreach ($loc in $aloc)
        {
            $loc = $loc.trim()
            $FolderName = "$Country/$loc/$ProjectName"
            
            CreateProjectStructure -sdkServer $sdkServer -sitecode $siteCode -FolderName $FolderName -globalproject 'n' -WQLWhere $WQLWhere
        }
    }

    [Environment]::SetEnvironmentVariable("SEE_MASK_NOZONECHECKS", "0", "Process")

    Write-Log -Message "Execution of $scriptName terminated"
}
finally
{
    $module = Get-Module -name Functions | where-object {$_.ModuleType -eq "Script"}
    if ($module -ne $null) 
    { 
        if ($module.Path.ToLower() -eq ($MediaFolder.ToLower() + "scripts\functions.ps1")) { Remove-Module $module }
    }
}     